//
//  NSString+Util.m
//  NewHelome
//
//  Created by kele on 14-9-17.
//  Copyright (c) 2014年 jetxiao. All rights reserved.
//

#import "NSString+Util.h"
#import <CommonCrypto/CommonDigest.h>
//#import "GTMBase64.h"

@implementation NSString (Util)

- (BOOL)hasValue {
    return ([self isKindOfClass:[NSString class]] && self.length > 0);
}

- (BOOL)isPhone {
    NSString *regex = @"((\\d{11})|^((\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})|(\\d{4}|\\d{3})-(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1})|(\\d{7,8})-(\\d{4}|\\d{3}|\\d{2}|\\d{1}))$)";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    BOOL isMatch = [pred evaluateWithObject:self];
    return isMatch;
}

- (BOOL)containsChineseCharacters {
    return [[NSPredicate predicateWithFormat:@"self matches %@",@".*[\\u4e00-\\u9fa5]+.*"] evaluateWithObject:self];
}


- (BOOL)isChineseIDCard {
    BOOL res = NO;
    if (self.hasValue) {
        NSString * numbers = [self numbersFormat];
        if ([self hasSuffix:@"x"] || [self hasSuffix:@"X"]) {
            if (numbers.hasValue) {
                res = (numbers.length == 14 || numbers.length == 17);
            }
        } else {
            if (numbers.hasValue) {
                res = (numbers.length == 15 || numbers.length == 18);
            }
        }
    }
    return res;
}

- (NSString *)numbersFormat {
    NSString * originStr = [NSString stringWithFormat:@"%@",self];
    NSMutableString * strippedString = [NSMutableString stringWithCapacity:originStr.length];
    NSScanner * scanner = [NSScanner scannerWithString:originStr];
    NSCharacterSet * numbers = [NSCharacterSet characterSetWithCharactersInString:@"0123456789"];
    while ([scanner isAtEnd] == NO) {
        NSString * buffer;
        if ([scanner scanCharactersFromSet:numbers intoString:&buffer]) {
            [strippedString appendString:buffer];
        } else {
            [scanner setScanLocation:([scanner scanLocation] + 1)];
        }
    }
    return strippedString;
}


- (NSString *)subCharacterFromIndex:(NSUInteger)aIndex {
    NSUInteger count = 0;
    for (NSUInteger index = 0; index < [self length]; ++index) {
        if([[self substringWithRange:NSMakeRange(index, 1)] containsChineseCharacters]) {
            count += 2;
        }
        else {
            ++count;
        }
        if(count > aIndex) {
            break;
        }
    }
    return [self substringToIndex:count];
}

- (NSUInteger)wordCount
{
    __block NSUInteger count=0;
    [self enumerateSubstringsInRange:NSMakeRange(0, self.length) options:NSStringEnumerationByWords usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
        ++count;
    }];
    return count;
}

+ (BOOL) isBlankString:(NSString *)string
{
    if (string == nil || string == NULL) {
        return YES;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return YES;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]] length]==0) {
        return YES;
    }
    return NO;
}

+ (NSString *)converNumber:(NSNumber *)aNumber,... {
    if(![aNumber isKindOfClass:[NSNumber class]]) {
        if([aNumber isKindOfClass:[NSString class]]) {
            return (NSString *)aNumber;
        }
        return nil;
    }
    va_list args;
    va_start(args, aNumber);
    int decimal = va_arg(args, int);
    va_end(args);
    if (strcmp([aNumber objCType], @encode(bool)) == 0 || strcmp([aNumber objCType], @encode(BOOL)) == 0) {
        return [NSString stringWithFormat:@"%d",[aNumber boolValue]];
    }
    else if (strcmp([aNumber objCType], @encode(char)) == 0) {
        return [NSString stringWithFormat:@"%c",[aNumber charValue]];
    }
    else if (strcmp([aNumber objCType], @encode(short)) == 0) {
        return [NSString stringWithFormat:@"%d",[aNumber shortValue]];
    }
    else if(strcmp([aNumber objCType], @encode(int)) == 0) {
        return [NSString stringWithFormat:@"%d",[aNumber intValue]];
    }
    else if (strcmp([aNumber objCType], @encode(long)) == 0) {
        return [NSString stringWithFormat:@"%ld",[aNumber longValue]];
    }
    else if (strcmp([aNumber objCType], @encode(double)) == 0) {
        double processEim = 0;
        //        processEim = [aNumber doubleValue];
        
        long decimalPow = pow(10, decimal);
        processEim = round([aNumber floatValue] * decimalPow) / decimalPow;
        
        return [NSString stringWithFormat:@"%f",processEim];
    }
    else if (strcmp([aNumber objCType], @encode(float)) == 0) {
        float processEim = 0;
        //        processEim = [aNumber floatValue];
        
        long decimalPow = pow(10, decimal);
        processEim = round([aNumber floatValue] * decimalPow) / decimalPow;
        
        return [NSString stringWithFormat:@"%f",processEim];
    }
    else if (strcmp([aNumber objCType], @encode(unsigned short)) == 0) {
        return [NSString stringWithFormat:@"%d",[aNumber unsignedShortValue]];
    }
    else if (strcmp([aNumber objCType], @encode(unsigned int)) == 0) {
        return [NSString stringWithFormat:@"%u",[aNumber unsignedIntValue]];
    }
    else if (strcmp([aNumber objCType], @encode(unsigned long)) == 0) {
        return [NSString stringWithFormat:@"%lu",[aNumber unsignedLongValue]];
    }
    return nil;
}

+ (NSString *)backDefaultIfNilWithString:(NSString *)string defaultString:(NSString *)defaultString {
    return [NSString isBlankString:string] ? defaultString : string;
}

+ (NSString *)parseDateFormatWithDate:(NSDate *)date converToFormat:(NSString *)converFormat {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = converFormat;
    return [dateFormatter stringFromDate:date];
}

- (NSString *)parseDateFormatWithFormat:(NSString *)converFormat {
    
    if([NSString isBlankString:self]) {
        return nil;
    }
    
    if([NSString isBlankString:converFormat]) {
        return self;
    }
    
    __block NSString *dateFormate = self;
    NSArray *dateForamateKey = @[@"yyyy",@"MM",@"dd",@"HH",@"mm",@"ss"];
    NSError *error = nil;
    NSRegularExpression *regularExpression = [NSRegularExpression regularExpressionWithPattern:@"\\d+" options:NSRegularExpressionCaseInsensitive error:&error];
    if(error) {
        return nil;
    }
    NSArray *matchesArray = [regularExpression matchesInString:self options:NSMatchingReportProgress range:NSMakeRange(0, self.length)];
    [matchesArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        NSTextCheckingResult *result = (NSTextCheckingResult *)obj;
        dateFormate = [dateFormate stringByReplacingOccurrencesOfString:[self substringWithRange:result.range] withString:dateForamateKey[idx]];
    }];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = dateFormate;
    NSDate *date = [dateFormatter dateFromString:self];
    if(date) {
        if(![NSString isBlankString:converFormat]) {
            dateFormatter.dateFormat = converFormat;
        }
        return  [dateFormatter stringFromDate:date];
    }
    return nil;
}

- (NSString *)trim {
    return [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}

- (NSString*)urlDecode
{
    return [self stringByReplacingPercentEscapesUsingEncoding:
            NSUTF8StringEncoding];
}

- (NSString *)urlEncode
{
    return [self stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

- (NSString *)md5
{
    unsigned char result[CC_MD5_DIGEST_LENGTH];
    const char *bytes = [self UTF8String];
    CC_MD5(bytes, (CC_LONG)strlen(bytes), result);
    
    return [NSString stringWithFormat:
            @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3], result[4],
            result[5], result[6], result[7], result[8], result[9],
            result[10], result[11], result[12], result[13], result[14], result[15]];
}

- (NSString *)sha1
{
    const char *cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    
    NSData *data = [NSData dataWithBytes:cstr length:self.length];
    //使用对应的CC_SHA1,CC_SHA256,CC_SHA384,CC_SHA512的长度分别是20,32,48,64
    uint8_t digest[CC_SHA1_DIGEST_LENGTH];
    //使用对应的CC_SHA256,CC_SHA384,CC_SHA512
    NSInteger len = data.length;
    CC_SHA1(data.bytes, len, digest);
    
    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++)
        [output appendFormat:@"%02X", digest[i]];
    
    return output;
}

- (BOOL)isVaildMail
{
    return [[NSPredicate predicateWithFormat:@"self matches %@",@"^[^@]+@[^@]+$"] evaluateWithObject:self];
}

- (BOOL)isVaildTel
{
    return [[NSPredicate predicateWithFormat:@"self matches %@",@"1\\d{10}"] evaluateWithObject:self];
}

- (BOOL)isChinese
{
    return [[NSPredicate predicateWithFormat:@"self matches %@",@"[\u4e00-\u9fa5]+"] evaluateWithObject:self];
}

- (NSString *)replaceBlank
{
    return [self stringByReplacingOccurrencesOfString:@" " withString:@""];
}

- (NSString *)replaceNull {
    return [self stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
}

- (NSString *)filterNonNumber {
    NSString *stringFliterInValidNumber = [self stringByReplacingOccurrencesOfString:@"\\D" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, self.length)];
    return stringFliterInValidNumber;
    
}
- (CGSize)sizeWithFont:(UIFont *)font maxW:(CGFloat)maxW {
    NSMutableDictionary *attrs = [NSMutableDictionary dictionary];
    attrs[NSFontAttributeName] = font;
    CGSize maxSize = CGSizeMake(maxW, MAXFLOAT);
    return [self boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:attrs context:nil].size;
}

- (CGSize)sizeWithFont:(UIFont *)font {
    return [self sizeWithFont:font maxW:MAXFLOAT];
}

- (void)phoneCall {
    if (self.length == 11) {
        NSMutableString * str = [[NSMutableString alloc] initWithFormat:@"telprompt://%@", self];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:str]];
    }
}

+ (NSString *)parseDateSiceNowWithTimerInterval:(NSTimeInterval)timerInterval {
    
    if(timerInterval == 0) {
        return nil;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timerInterval];
    if(date == nil) {
        return @"";
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
    NSTimeInterval currentTimeInterval = [[NSDate date] timeIntervalSince1970],
    minutes = 60,
    hour = 60 * minutes,
    day = 24 * hour;
    if(timerInterval > currentTimeInterval - minutes) {
        return @"刚刚";
    }
    else if (timerInterval > currentTimeInterval - hour) {
        return [NSString stringWithFormat:@"%d分钟前",(int)((currentTimeInterval - timerInterval) / minutes)];
    }
    else if (timerInterval > currentTimeInterval - day) {
        return [NSString stringWithFormat:@"%d小时前",(int)((currentTimeInterval - timerInterval) / hour)];
    }
    else if (timerInterval > currentTimeInterval *365) {
        dateFormatter.dateFormat = @"yyyy.MM.dd HH:mm";
        return [dateFormatter stringFromDate:date];
    }
    dateFormatter.dateFormat = @"MM.dd HH:mm";
    return [dateFormatter stringFromDate:date];
}

+ (NSString *)parseDateSiceNowWeekWithTimerInterval:(NSTimeInterval)timerInterval {
    if(timerInterval == 0) {
        return nil;
    }
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timerInterval];
    
    if(date == nil) {
        return @"";
    }
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm";
    NSTimeInterval currentTimeInterval = [[NSDate date] timeIntervalSince1970],
    minutes = 60,
    hour = 60 * minutes,
    day = 24 * hour;
    
    NSString *dayString = [[NSString alloc] init];
    NSString *weekString = [NSString featureWeekdayWithDate:date];
    NSString *timeString = [[NSString alloc] init];  
    if (timerInterval > currentTimeInterval - day) {
        if ((currentTimeInterval - timerInterval) / hour < 24 && (currentTimeInterval - timerInterval) / hour > 0) {
            dateFormatter.dateFormat = @"HH:mm";
            timeString = [dateFormatter stringFromDate:date];
            
            dayString = [[[@"今天 " stringByAppendingString:weekString] stringByAppendingString:@" "] stringByAppendingString:timeString];
            
            return dayString;
        }
    }
    dateFormatter.dateFormat = @"yyyy.MM.dd";
    dayString = [dateFormatter stringFromDate:date];
    
    dateFormatter.dateFormat = @"HH:mm";
    timeString = [dateFormatter stringFromDate:date];
    
    dayString = [[[[dayString stringByAppendingString:@" "] stringByAppendingString:weekString] stringByAppendingString:@" "] stringByAppendingString:timeString];
    return dayString;
}
+ (NSString *)featureWeekdayWithDate:(NSDate *)endDate {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps;
    
    comps = [calendar components:(NSCalendarUnitWeekOfYear | NSCalendarUnitWeekday | NSCalendarUnitWeekdayOrdinal)
                       fromDate:endDate];
    NSInteger weekday = [comps weekday]; // 星期几（注意，周日是“1”，周一是“2”。。。。）
    NSString *week = @"";
    switch (weekday) {
        case 1:
            week = @"星期日";
            break;
        case 2:
            week = @"星期一";
            break;
        case 3:
            week = @"星期二";
            break;
        case 4:
            week = @"星期三";
            break;
        case 5:
            week = @"星期四";
            break;
        case 6:
            week = @"星期五";
            break;
        case 7:
            week = @"星期六";
            break;
            
        default:
            break;
    }
    return week;
//    long days = [NSString daysFromDate:[NSDate date] toDate:endDate];
//    long day = days >= 7 ? days % 7 : days;
//    long week = [NSString getNowWeekday] + day;
//    if (week >7) {
//        week = week - 7;
//    }
//    switch (week) {
//        case 1:
//            return @"星期日";
//            break;
//        case 2:
//            return @"星期一";
//            break;
//        case 3:
//            return @"星期二";
//            break;
//        case 4:
//            return @"星期三";
//            break;
//        case 5:
//            return @"星期四";
//            break;
//        case 6:
//            return @"星期五";
//            break;
//        case 7:
//            return @"星期六";
//            break;
//        default:
//            break;
//    }
//    return nil;
}
+ (NSInteger)daysFromDate:(NSDate *)startDate toDate:(NSDate *)endDate {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSTimeInterval time = [endDate timeIntervalSinceDate:startDate];
    int days = ((int)time) / (3600 * 24);
    int hours = ((int)time) % (3600 * 24) / 3600;
    int minute = ((int)time) % (3600 * 24) / 3600 / 60;
    if (days <= 0 && hours <= 0 && minute <= 0) {
        return 0;
    } else {
        return days + 1;
    }
}
+ (NSInteger)getNowWeekday {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay | NSCalendarUnitWeekday |
    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDate *now = [NSDate date];
    calendar.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
    comps = [calendar components:unitFlags fromDate:now];
    return [comps weekday];
}

+ (NSInteger)getNumberOfDaysInMonth {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDate *currentDate = [NSDate date];
    NSRange range = [calendar rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:currentDate];
    return range.length;
}
+ (NSArray *)getAllDaysWithCalender {
    NSUInteger dayCount = [NSString getNumberOfDaysInMonth];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    NSDate *currentDate = [NSDate date];
    [formatter setDateFormat:@"yyyy-MM"];
    NSString *str = [formatter stringFromDate:currentDate];
    [formatter setDateFormat:@"yyyy-MM-dd"];
    NSMutableArray *allDaysArray = [[NSMutableArray alloc] init];
    for (NSInteger i = 1; i <= dayCount; i++) {
        NSString *sr = [NSString stringWithFormat:@"%@-%@", str, @(i)];
        NSDate *suDate = [formatter dateFromString:sr];
        [allDaysArray addObject:[NSString getWeekDayWithDate:suDate]];
    }
    return (NSArray *)allDaysArray;
}
+ (id)getWeekDayWithDate:(NSDate *)date {
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = [calendar components:NSCalendarUnitWeekday fromDate:date];
    return @([comps weekday]);
}

+ (NSString *)parseDateFormatWithTimeInterval:(NSTimeInterval)interval converFormat:(NSString *)converFormat {
    
    if(interval == 0 || [NSString isBlankString:converFormat]) {
        return nil;
    }
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    dateFormatter.dateFormat = converFormat;
    return [dateFormatter stringFromDate:date];
}

+ (NSString *)filterSpecialCharWithString:(NSString *)string {
    
    return [string stringByReplacingOccurrencesOfString:@"[^\\u0020-\\u007E\\u00A0-\\u00BE\\u2E80-\\uA4CF\\uF900-\\uFAFF\\uFE30-\\uFE4F\\uFF00-\\uFFEF\\u0080-\\u009F\\u2000-\\u201f]" withString:@"" options:NSRegularExpressionSearch range:NSMakeRange(0, string.length)];
}

+ (NSString *)messageCaptchaSign:(NSString *)mobile type:(NSString *)type nonceStr:(NSString *)nonceStr timestamp:(NSString *)timestamp {
    //取时间戳中间位的数
    NSInteger middleInteger = [timestamp substringWithRange:NSMakeRange(6, 1)].integerValue;
    //判断奇偶数 YES为奇数，NO为偶数
    BOOL odevity = middleInteger % 2;
    NSInteger startInteger = odevity == YES ? 1 : 0;
    NSInteger a = 1;
    for (int i = (int)startInteger; i < timestamp.length; i++) {
        NSString * str = [timestamp substringWithRange:NSMakeRange(i, 1)];
        NSInteger b = str.integerValue;
        if (b != 0) a *= b;
        i++;
    }
    NSString * skey = [NSString stringWithFormat:@"%@", @(a)];
    NSString * sign = [NSString stringWithFormat:@"mobile=%@&nonceStr=%@&timestamp=%@&typeCode=%@&skey=%@", mobile, nonceStr, timestamp, type, skey];
    
    return sign;
}

+ (NSString *)uuidString {
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString *)uuid_string_ref];
    CFRelease(uuid_ref);
    CFRelease(uuid_string_ref);
    return [uuid lowercaseString];
}

+ (BOOL)judgePassWordLegal:(NSString *)pass {
    BOOL result = false;
    if ([pass length] >= 6){
        // 判断长度大于6位后再接着判断是否同时包含数字和字符
        //        NSString * regex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$";
        NSString * regex = @"^[A-Za-z0-9\u4E00-\u9FA5_-]+$";
        //        NSString * regex = @"[a-z][A-Z][0-9]";
        NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
        result = [pred evaluateWithObject:pass];
    }
    return result;
}

+ (BOOL)isPureInt:(NSString *)string {
    NSScanner* scan = [NSScanner scannerWithString:string]; //定义一个NSScanner，扫描string
    int val;
    return[scan scanInt:&val] && [scan isAtEnd];
}

+ (NSString *)changePayMoneyString:(NSString *)payMoneyString {
    NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
    formatter.numberStyle = NSNumberFormatterDecimalStyle;
    NSString *newAmount = [formatter stringFromNumber:[NSNumber numberWithInteger:[payMoneyString integerValue]]];
    return newAmount;
}

+ (NSString*)strmethodComma:(NSString*)string {
    NSString * sign = nil;
    NSString *originalString = string;
    if ([originalString containsString:@"."]) {
        NSRange range = [originalString rangeOfString:@"."];
        originalString = [originalString substringFromIndex:range.location];
        
        sign = [[self changePayMoneyString:string] stringByAppendingString:originalString];//[[@"¥" stringByAppendingString:[self changePayMoneyString:string]] stringByAppendingString:originalString];
    } else {
        sign = [self changePayMoneyString:string];//[@"¥" stringByAppendingString:[self changePayMoneyString:string]];
    }
    return sign;
}

+ (NSString *)moenyAndPoint:(NSString *)string {
    NSNumberFormatter *moneyFormatter = [[NSNumberFormatter alloc] init];
    moneyFormatter.positiveFormat = @"###,##0.00";
    CGFloat moneyFloat = [string doubleValue] /100;
    NSString *moneyString = [moneyFormatter stringFromNumber:@(moneyFloat)];
    return moneyString;
}

+ (NSString *)filterCharactor:(NSString *)string withRegex:(NSString *)regexStr{
    NSString *filterText = string;
    NSError *error = NULL;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    NSString *result = [regex stringByReplacingMatchesInString:filterText options:NSMatchingReportCompletion range:NSMakeRange(0, filterText.length) withTemplate:@""];
    return result;
}

+ (NSString *)dateChangeToTimeString {
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval timeInterval = [date timeIntervalSince1970] *1000;
    return [NSString stringWithFormat:@"%.0f", timeInterval];
}

+ (NSString *)getCurrentTimes:(NSString *)dateFormat {
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:dateFormat];
    NSDate *datenow = [NSDate date];
    NSString *currentTimeString = [formatter stringFromDate:datenow];
    
    return currentTimeString;
    
}

+ (NSTimeInterval)dateChangeToTimerInterval:(NSString *)timerStr {
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *inputDate = [inputFormatter dateFromString:timerStr];
    NSTimeInterval timeStamp = [inputDate timeIntervalSince1970];
    return timeStamp;
}

- (NSString *)stringAndDateChange:(NSString *)timeStr dateFormat:(NSString *)dateFormat {
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *inputDate = [inputFormatter dateFromString:timeStr];
    NSTimeInterval timeStamp = [inputDate timeIntervalSince1970] *1000;
    
    NSDate *date = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval currentStamp = [date timeIntervalSince1970] *1000;
    
    NSString *_timeStr;

    _timeStr = [NSString stringWithFormat:@"%@", [self convertSecondsToTime:timeStamp Format:dateFormat]];
    return _timeStr;
}
- (NSString *)convertSecondsToTime:(long long)time Format:(NSString*)dateFormat {
    NSDate *d = [[NSDate alloc]initWithTimeIntervalSince1970:time/1000.0];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:dateFormat];
    NSString *timeString = [formatter stringFromDate:d];
    
    return timeString;
}

- (NSArray *)componentsSeparatedFromString:(NSString *)fromString toString:(NSString *)toString {
    if (!fromString || !toString || fromString.length == 0 || toString.length == 0) {
        return nil;
    }
    NSMutableArray *subStringsArray = [[NSMutableArray alloc] init];
    NSString *tempString = self;
    NSRange range = [tempString rangeOfString:fromString];
    while (range.location != NSNotFound) {
        tempString = [tempString substringFromIndex:(range.location + range.length)];
        range = [tempString rangeOfString:toString];
        if (range.location != NSNotFound) {
            [subStringsArray addObject:[tempString substringToIndex:range.location]];
            range = [tempString rangeOfString:fromString];
        }
        else
        {
            break;
        }
    }
    return subStringsArray;
}

- (NSString *)dealWithString:(NSString *)number {
    NSString *doneTitle = @"";
    int count = 0;
    for (int i = 0; i < number.length; i++) {
        count ++;
        doneTitle = [doneTitle stringByAppendingString:[number substringWithRange:NSMakeRange(i, 1)]];
        if (count == 4) {
            doneTitle = [NSString stringWithFormat:@"%@ ", doneTitle];
            count = 0;
        }
    }
    return doneTitle;
}

+ (NSString *)updateTimeForRow:(NSString *)createTimeString {
    NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970];
    
    NSTimeInterval createTime = [createTimeString longLongValue];
    if (createTimeString.length >= 13) {
        createTime = [createTimeString longLongValue]/1000;
    }
    NSTimeInterval time = currentTime - createTime;
    NSInteger min = time / 60;
    // 分钟
    if (min < 10) {
        return @"刚刚";
    } else if (min < 60) {
        return [NSString stringWithFormat:@"%ld分钟前",min];
    }
    
    // 小时
    NSInteger hours = time/3600;
    if (hours<24) {
        return [NSString stringWithFormat:@"%ld小时前",hours];
    }
    
    // 天数
    NSInteger days = time/3600/24;
    if (days < 7) {
        return [NSString stringWithFormat:@"%ld天前",days];
    }
    
    
    NSDate *detailDate=[NSDate dateWithTimeIntervalSince1970:createTime];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"Asia/Beijing"];
    [dateFormatter setTimeZone:timeZone];
    
    // 月
    NSInteger months = time/3600/24/30;
    if (months < 12) {
        [dateFormatter setDateFormat:@"MM月dd日"];
        return [dateFormatter stringFromDate: detailDate];
    }
    
    // 年
    [dateFormatter setDateFormat:@"yyyy年MM月dd日"];
    return [dateFormatter stringFromDate: detailDate];
}

+ (BOOL)verifyIDCardNumber:(NSString *)value
{
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([value length] != 18) {
        return NO;
    }
    NSString *mmdd = @"(((0[13578]|1[02])(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)(0[1-9]|[12][0-9]|30))|(02(0[1-9]|[1][0-9]|2[0-8])))";
    NSString *leapMmdd = @"0229";
    NSString *year = @"(19|20)[0-9]{2}";
    NSString *leapYear = @"(19|20)(0[48]|[2468][048]|[13579][26])";
    NSString *yearMmdd = [NSString stringWithFormat:@"%@%@", year, mmdd];
    NSString *leapyearMmdd = [NSString stringWithFormat:@"%@%@", leapYear, leapMmdd];
    NSString *yyyyMmdd = [NSString stringWithFormat:@"((%@)|(%@)|(%@))", yearMmdd, leapyearMmdd, @"20000229"];
    NSString *area = @"(1[1-5]|2[1-3]|3[1-7]|4[1-6]|5[0-4]|6[1-5]|82|[7-9]1)[0-9]{4}";
    NSString *regex = [NSString stringWithFormat:@"%@%@%@", area, yyyyMmdd  , @"[0-9]{3}[0-9Xx]"];
    
    NSPredicate *regexTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    if (![regexTest evaluateWithObject:value]) {
        return NO;
    }
    int summary = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7
    + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9
    + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10
    + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5
    + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8
    + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4
    + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2
    + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6
    + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
    NSInteger remainder = summary % 11;
    NSString *checkBit = @"";
    NSString *checkString = @"10X98765432";
    checkBit = [checkString substringWithRange:NSMakeRange(remainder,1)];// 判断校验位
    return [checkBit isEqualToString:[[value substringWithRange:NSMakeRange(17,1)] uppercaseString]];
}

+ (NSString *)getIPAddress:(BOOL)preferIPv4 {
    NSArray *searchArray = preferIPv4 ?
    @[IOS_VPN @"/" IP_ADDR_IPv4, IOS_VPN @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6 ] :
    @[IOS_VPN @"/" IP_ADDR_IPv6, IOS_VPN @"/" IP_ADDR_IPv4, IOS_WIFI @"/" IP_ADDR_IPv6, IOS_WIFI @"/" IP_ADDR_IPv4, IOS_CELLULAR @"/" IP_ADDR_IPv6, IOS_CELLULAR @"/" IP_ADDR_IPv4 ] ;
    
    NSDictionary *addresses = [NSString getIPAddresses];
    
    __block NSString *address;
    [searchArray enumerateObjectsUsingBlock:^(NSString *key, NSUInteger idx, BOOL * _Nonnull stop) {
        address = addresses[key];
        // 筛选出IP地址格式
        if ([NSString isValidatIP:address]) *stop = YES;
    }];
    return address ? address : @"0.0.0.0";
}
+ (NSDictionary *)getIPAddresses {
    NSMutableDictionary *addresses = [NSMutableDictionary dictionaryWithCapacity:8];
    struct ifaddrs *interfaces;
    if (!getifaddrs(&interfaces)) {
        struct ifaddrs *interface;
        for (interface = interfaces; interface; interface = interface->ifa_next) {
            if (!(interface->ifa_flags & IFF_UP)) {
                continue;
            }
            const struct sockaddr_in *addr = (const struct sockaddr_in *)interface->ifa_addr;
            char addrBuf[MAX(INET_ADDRSTRLEN, INET6_ADDRSTRLEN)];
            if (addr && (addr->sin_family == AF_INET || addr->sin_family == AF_INET6)) {
                NSString *name = [NSString stringWithUTF8String:interface->ifa_name];
                NSString *type;
                if (addr->sin_family == AF_INET) {
                    if (inet_ntop(AF_INET, &addr->sin_addr, addrBuf, INET_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv4;
                        NSLog(@"ipv4 %@", name);
                    }
                } else {
                    const struct sockaddr_in6 *addr6 = (const struct sockaddr_in6 *)interface->ifa_addr;
                    if (inet_ntop(AF_INET6, &addr6->sin6_addr, addrBuf, INET6_ADDRSTRLEN)) {
                        type = IP_ADDR_IPv6;
                        NSLog(@"ipv6 %@", name);
                    }
                }
                if (type) {
                    NSString *key = [NSString stringWithFormat:@"%@/%@", name, type];
                    addresses[key] = [NSString stringWithUTF8String:addrBuf];
                }
            }
        }
        freeifaddrs(interfaces);
    }
    return [addresses count] ? addresses : nil;
}
+ (BOOL)isValidatIP:(NSString *)ipAddress {
    if (ipAddress.length == 0) {
        return NO;
    }
    NSString *urlRegEx = @"^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\."
    "([01]?\\d\\d?|2[0-4]\\d|25[0-5])$";
    
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:urlRegEx options:0 error:&error];
    
    if (regex != nil) {
        NSTextCheckingResult *firstMatch = [regex firstMatchInString:ipAddress options:0 range:NSMakeRange(0, [ipAddress length])];
        return firstMatch;
    }
    return NO;
}

- (NSString *)changePhone {
    if (self.length < 11) {
        return self;
    }
    NSString *numberString = [self stringByReplacingCharactersInRange:NSMakeRange(3, 4) withString:@"****"];
    return numberString;
}

@end
